from tortoise import models, fields
from tortoise.contrib.pydantic import pydantic_model_creator


# pipenv install tortoise-orm[aiomysql]
class Post(models.Model):
    id = fields.IntField(pk=True)
    title = fields.CharField(max_length=50)
    content = fields.TextField()
    created_at = fields.DatetimeField(auto_now_add=True)

    # 需要明确指定返回值类型，不然PydanticMeta的computed元组中的字段在响应结果集中不会出现
    # https://tortoise-orm.readthedocs.io/en/latest/contrib/pydantic.html#pydanticmeta-callables
    def pub_date(self) -> str:
        return self.created_at.strftime('%Y-%m-%d %H:%M:%S')

    class PydanticMeta:
        # 指明该字段是计算后得到的结果
        computed = ('pub_date',)
        # 结果集中不显示created_at字段，显示pub_date
        exclude = ('created_at',)
        # ordering = ('-id',)


# 根据tortoise模型创建pydantic模型
Post_Pydantic = pydantic_model_creator(Post, name='Post')
# 去掉只读字段，如ID字段，用户上传数据时不需要指定该字段
PostIn_Pydantic = pydantic_model_creator(Post, name='PostIn', exclude_readonly=True)
